package com.fingard.dsp.bank.directbank.cib01;

import com.alibaba.fastjson.JSON;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.net.FormSubmit;
import netbank.firm.service.FileService;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/9/20.
 */
public class CIB01ScheduleTask extends CIB01Base implements IScheduleTask {
    @Override
    public void execTask(TaskTimerSet timerSet) {
        if (timerSet.taskNameList.toLowerCase().contains("pushreceipt")) {
            qryReceipt();
        }
    }

    private String receiptSaveToMainDir = "";

    public void qryReceipt() {
        try {
            //定时任务一：根据批次号同步电子回单
            synchReceipt();

            //定时任务二：下载银行服务器电子回单文件
            receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
            if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                    if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                        getStatement();
                    } else {
                        WriteBankLogLn("DSPSystem未配置回单文件推送地址。");
                    }
                } else {
                    WriteBankLogLn("DSPSystem未配置回单文件共享目录。");
                }
            } else {
                WriteBankLogLn("DSPSystem未配置回单文件下载保存主目录。");
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        }
    }

    /**
     * 根据批次号同步电子回单
     */
    private void synchReceipt() {
        try {
            WriteBankLogLn("定时任务一：根据批次号同步电子回单开始");
            StringBuilder fileNameList = new StringBuilder();//记录下载文件名
            int fileCount = 0;//记录下载数量
            //获取批次号
            String path = FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "dataFile" + File.separator + bankFront.code + File.separator + "cltRefNoFile" + File.separator;
            File file = new File(path);
            File[] tempList = file.listFiles();
            if (tempList == null || tempList.length == 0) {
                WriteBankLogLn("文件夹没有需要同步电子回单的账户文件夹" + path);
                return;
            }
            //根据批次号请求同步回单
            for (File files : tempList) {
                String dataFilePath = path + File.separator + files.getName();
                String fileContent = "";
                if (FileHelper.existFile(dataFilePath)) {
                    fileContent = FtpUtil.getTextFromFile(dataFilePath, getCharset());
                }
                String cltRefNo = fileContent.replace("\r\n", "");
                if (!"".equals(cltRefNo)) {
                    boolean flag = true;
                    int page = 1;//请求页数
                    while (flag) {
                        //1.2 同步电子回单
                        CIB01Header header2 = new CIB01Header();
                        XmlTextWriter xmlWriter2 = new XmlTextWriter();//发银行报文的XML对象
                        writeHeaderReceipt(xmlWriter2, header2);
                        xmlWriter2.writeStartElement("SECURITIES_MSGSRQV1");
                        xmlWriter2.writeStartElement(CIB01TransType.Receipt);
                        xmlWriter2.writeElementString("TRNUID", getQryTransID());//流水号
                        //xmlWriter2.writeStartElement("RQBODY");//查询页
                        xmlWriter2.writeElementAttribute("RQBODY", "PAGE", String.valueOf(page));
                        xmlWriter2.writeElementString("CLT_REF_NO", cltRefNo);//批次号
                        xmlWriter2.writeEndElement();
                        xmlWriter2.writeEndElement();
                        xmlWriter2.writeEndElement();
                        xmlWriter2.writeEndDocument();
                        //StringBuffer sb=new StringBuffer(xmlWriter2.toXmlString());
                        //int rqIndex=xmlWriter2.toXmlString().indexOf("RQBODY")+"RQBODY".length();
                        //sb.insert(rqIndex," PAGE=\""+page+"\"");
                        String[] tmpStrRet2 = sendToBankReceipt(xmlWriter2.toXmlString());

                        //测试
                        //tmpStrRet2[0]="";
                        //tmpStrRet2[1]="<?xml version=\"1.0\" encoding=\"utf-8\"?><FOX>  <SIGNONMSGSRSV1>    <SONRS>      <STATUS>        <CODE>0</CODE>        <SEVERITY>INFO</SEVERITY>      </STATUS>      <DTSERVER>2017-09-05 19:11:31</DTSERVER>    </SONRS>  </SIGNONMSGSRSV1>  <SECURITIES_MSGSRSV1>    <ASYNRECEIPTINFOTRNRS>      <TRNUID>electronicReceipt2017005</TRNUID>      <STATUS>        <CODE>0</CODE>        <SEVERITY>INFO</SEVERITY>        <MESSAGE>处理成功！</MESSAGE>      </STATUS>      <RSBODY MORE=\"N\">        <STATUS>2</STATUS>        <SRVC_NO>900002837247</SRVC_NO>        <FILESUM>1</FILESUM>        <ACCTID>117010100100196080</ACCTID>        <RECEIPT_TYPE>01</RECEIPT_TYPE>        <DUE_DATE>2017-09-12</DUE_DATE>        <CONTENT>          <SEQ>1</SEQ>          <FILE_ID>101_AWYWgFOqT#o</FILE_ID>          <FILE_NAME>171b1_117010100100307217081126_20180926_1.zip</FILE_NAME>        </CONTENT>      </RSBODY>    </ASYNRECEIPTINFOTRNRS>  </SECURITIES_MSGSRSV1></FOX>\n";

                        if (tmpStrRet2[0].length() == 0) {
                            StringBuilder tmpSbMsg2 = new StringBuilder();
                            XmlTextReader tmpBkReader2 = loadBankRespXmlReader(tmpStrRet2[1], tmpSbMsg2);
                            if (tmpBkReader2 != null) {
                                String trspCod = tmpBkReader2.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                                String trspMsg = tmpBkReader2.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/SEVERITY");
                                if ("0".equals(trspCod)) {
                                    String rspCod = tmpBkReader2.getFirstText("/FOX/SECURITIES_MSGSRSV1/ASYNRECEIPTINFOTRNRS/STATUS/CODE");
                                    String rspMsg = tmpBkReader2.getFirstText("/FOX/SECURITIES_MSGSRSV1/ASYNRECEIPTINFOTRNRS/STATUS/MESSAGE");

                                    if ("0".equals(rspCod)) {
                                        //是否下一页标识 Y：有 N：无
                                        tmpBkReader2.read("/FOX/SECURITIES_MSGSRSV1/ASYNRECEIPTINFOTRNRS/RSBODY");
                                        XElement readXElement2 = tmpBkReader2.readedXElement;
                                        String more = readXElement2.hashMapAttributes.get("MORE");
                                        //int where=tmpStrRet2[1].indexOf("MORE=\"")+"MORE=\"".length();
                                        //String more=tmpStrRet2[1].substring(where,where+1);
                                        if ("Y".equals(more.trim())) {
                                            page++;//有下一页，查询页码+1
                                        } else {
                                            flag = false;//无下一页，最后一次循环
                                        }

                                        ArrayList<XElement> list = readXElement2.getChildList("CONTENT");

                                        for (int i = 0; i < list.size(); i++) {
                                            //XElement readXElement = tmpBkReader2.readedXElement;
                                            //文件名
                                            String fileName = list.get(i).getSingleTextNotNull("FILE_NAME");
                                            //文件id
                                            String fileId = list.get(i).getSingleTextNotNull("FILE_ID");
                                            generateReceiptCodeFile("", fileName, fileId);
                                            fileNameList.append(fileName + ",");
                                            fileCount++;
                                        }
                                        //成功同步电子回单并且不存在下一页数据，删除临时存放批次号的文件
                                        if ("N".equals(more.trim())) {
                                            if (FileHelper.deleteFileIfExists(dataFilePath)) {
                                                WriteBankLogLn("批次号" + cltRefNo + "已无下一页数据，删除临时文件：" + dataFilePath);
                                            }
                                        }
                                    } else {
                                        WriteBankLogLn(rspMsg);
                                        flag = false;
                                    }
                                } else {
                                    WriteBankLogLn(trspMsg);
                                    flag = false;
                                }
                            } else {
                                WriteBankLogLn(tmpSbMsg2.toString());
                                flag = false;
                            }
                        } else {
                            WriteBankLogLn(tmpStrRet2[1]);
                            flag = false;
                        }
                    }
                } else {
                    WriteBankLogLn("批次号为空");
                }
            }
            WriteBankLogLn("成功下载了" + fileCount + "个文件到银行服务器上，名称为：" + fileNameList.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载银行服务器电子回单文件
     */
    private void getStatement() {
        String uploadType = SmbFileUtil.getUploadType();
        try {
            WriteBankLogLn("定时任务二：下载银行服务器电子回单文件开始");
            //定义返回ATS的json字符串
            StringBuilder json = new StringBuilder();
            if(getBankConfig().getValueAsBool("receiptPushHasTenantId")){
                json.append("tenantId="+FGBiz.dspCenter.dspSet.tenant+"&transType=downloadreceipt&data={\"rows\":[");
            }else{
                json.append("transType=downloadreceipt&data={\"rows\":[");
            }
            List<File> fileList = new ArrayList<File>();
            //记录下载银行服务器上文件的名称
            StringBuilder sb = new StringBuilder();
            //记录成功处理回单文件的名称
            StringBuilder sb2 = new StringBuilder();
            //获取fileName和fileId
            String path = FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "dataFile" + File.separator + bankFront.code + File.separator + "receiptDataFile" + File.separator;
            File file = new File(path);
            File[] tempList = file.listFiles();
            if (tempList == null || tempList.length == 0) {
                WriteBankLogLn("文件夹没有需要下载电子回单的账户文件夹" + path);
                return;
            }
            //请求下载文件
            for (File files : tempList) {
                String dataFilePath = path + File.separator + files.getName();
                String fileContent = "";
                if (FileHelper.existFile(dataFilePath)) {
                    fileContent = FtpUtil.getTextFromFile(dataFilePath, getCharset());
                } else {
                    WriteBankLogLn("文件夹电子回单的账户文件夹已下载" + dataFilePath);
                    return;
                }
                String fileName = fileContent.split("\\|")[0];
                String fileId = fileContent.split("\\|")[1].replace("\r\n", "");
                try {
                    //调用方法下载压缩文件
                    FileService service = new FileService();
                    String filePath2 = service.downloadFile(fileName, fileId);
                    WriteBankLogLn("下载成功,文件路径为" + filePath2);
                    sb.append(fileName + ",");
                    fileList.add(new File(filePath2.replace(fileId, fileId.replace("_", "****"))));
                    //删除带.gz的压缩包 ?
                    File fileGz = new File(filePath2 + ".gz");
                    if (FileHelper.deleteFileIfExists(fileGz.getPath())) {
                        WriteBankLogLn("已删除临时文件：" + fileGz.getPath());
                    }
                    //删除已下载的临时存放文件名和id的文件
                    if (FileHelper.deleteFileIfExists(dataFilePath)) {
                        WriteBankLogLn("已删除临时文件：" + dataFilePath);
                    }
                } catch (Exception ex) {
                    WriteBankLogLn("下载文件异常，异常为：" + ex);
                    ex.printStackTrace();
                }
            }
            WriteBankLogLn("已成功下载电子回单的文件名：" + sb.toString());
            //fileList.add(new File("D:\\101****AWX6mz8bHbN_6a001_117010100100050880_20180921_1.zip"));
            //处理下载的文件
            int tmpFileCount = 0;
            for (int i = 0; i < fileList.size(); i++) {
                //boolean isZip = true;
                if (FileHelper.existFile(fileList.get(i).getPath().replace("****", "_"))) {
                    String fileName = fileList.get(i).getName();
                    //根据压缩文件名获取账号
                    String[] nameArray = fileName.split("_");
                    String actNum = nameArray[2];
                    fileName = fileName.replace("****", "_");
                    String tranDate = "";
                    String tmpDateFileDir = getTempFileDirectory();
                    WriteBankLogLn("解压至：" + tmpDateFileDir + File.separator + fileName);
                    //解压
                    ZipHelper.unzipFile(fileList.get(i).getPath().replace("****", "_"), tmpDateFileDir);
                    File receiptDir = new File(tmpDateFileDir + File.separator + fileName.replace(".zip", ""));
                    if (!receiptDir.exists()) {
                        WriteBankLogLn("不存在回单目录:" + receiptDir.getName());
                        continue;
                    }
                    //获取解压后的文件
                    File[] receiptFiles = receiptDir.listFiles();
                    if (receiptFiles != null && receiptFiles.length > 0) {
                        WriteBankLogLn(fileName + "解压后共有" + receiptFiles.length + "个文件");
                        //循环处理解压后的文件：上传至共享目录，拼接返回ATS的字符串信息
                        for (File receiptFile : receiptFiles) {
                            if (receiptFile.getName().contains(fileName.replace(".zip", ""))) {
                                WriteBankLogLn("解压后pdf文件名称为：" + receiptFile.getName() + ",与压缩包名称：" + fileName + "相同，没有电子回单。");
                                //isZip = false;
                                continue;
                            } else {
                                String tmpByDate = Format.Date8Format.format(new Date());
                                tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + actNum + "/";
                                tranDate = receiptFile.getName().substring(0, 8);//获取回单日期
                                //上传文件到共享目录下
                                int result = -1;
                                String AtsFilePath = "";
                                if (receiptFile.exists()) {
                                    if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                        if ("smb".equals(uploadType)) {
                                            WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            result = SmbFileUtil.smbUploading(receiptFile.getPath(), tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                            AtsFilePath = tmpByDate + receiptFile.getName();
                                        }else if("localhost".equals(uploadType)){
                                            String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                            WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                            result = FileHelper.copyFile(receiptFile.getPath(), shareDir + tmpByDate + receiptFile.getName());
                                            AtsFilePath = tmpByDate + receiptFile.getName();
                                        } else {
                                            tmpByDate = tmpByDate.replaceAll(reqHeader.bankCode + "/", "");
                                            WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            Map<String, String> map = FormSubmit.fileUpload
                                                    (FGBiz.dspCenter.dspSet.receiptShareDir, actNum, receiptFile.getPath(), tmpByDate, receiptFile.getName(), getCharset());
                                            WriteBankLogStep3(JSON.toJSONString(map));
                                            if (map.keySet().size() != 0) {
                                                result = Integer.valueOf(map.get("respCode"));
                                                tmpByDate = map.get("remotePath");
                                                AtsFilePath = tmpByDate;
                                            } else {
                                                result = -1;
                                            }
                                        }
                                    }else{//上传FTP
                                        //ftp服务器
                                        FtpSet ftpSet = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                        WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet.upDir);
                                        //上传ftp服务器的地址
                                        String ftpFilePath = StringHelper.trimEndFileSp(ftpSet.upDir) + "/" +tmpByDate + receiptFile.getName();
                                        WriteBankLogLn("开始将回单"+receiptFile.getPath()+"上传至"+ftpFilePath);
                                        //上传至ftp
                                        result = FtpUtil.ftpUploading(ftpSet, receiptFile.getPath(), ftpFilePath);
                                        AtsFilePath = tmpByDate + receiptFile.getName();
                                    }
                                }
                                //上传成功处理
                                if (result == 0 || result == 1) {
                                    tmpFileCount++;
                                    if (result == 0) {
                                        WriteBankLogLn("文件上传成功");
                                    } else {
                                        WriteBankLogLn("文件已存在共享目录无需重复上传");
                                    }
                                    //推送数据给ATS处理
                                    json.append("{");
                                    json.append("\"actNum\":\"" + actNum + "\",");
                                    json.append("\"actCur\":\"" + getBankConfig().getMapKeyByValue("curActMapping", actNum) + "\",");
                                    json.append("\"receiptCode\":\"" + receiptFile.getName().replace(".pdf","").replace(".PDF","") + "\",");//回单编号
                                    json.append("\"receiptType\":\"" + "" + "\",");//回单类型  1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                    json.append("\"receiptState\":\"" + "" + "\",");//回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                    json.append("\"oppActName\":\"" + "" + "\",");
                                    json.append("\"oppActNum\":\"" + "" + "\",");
                                    json.append("\"amount\":\"" + "" + "\",");
                                    json.append("\"moneyway\":\"" + "" + "\",");
                                    String tranSeqNo=reqHeader.transSeqID;
                                    if(StringHelper.hasAnyChar(getBankConfig().getValueAsString("blnAndridAvaiDate"))){
                                        //回单时间
                                        int receiptDate = Integer.parseInt(tranDate);
                                        //生效时间
                                        int availDate = Integer.parseInt(getBankConfig().getValueAsString("blnAndridAvaiDate"));
                                        if (receiptDate >= availDate) {
                                            tranSeqNo=receiptFile.getName().replaceAll(".pdf","").replaceAll(".PDF","");
                                        }
                                    }
                                    json.append("\"tranSeqNo\":\"" + tranSeqNo + "\",");
                                    json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                    json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(tranDate)) + "\",");
                                    json.append("\"filePath\":\"" + AtsFilePath + "\",");//回单文件仓库存储路径
                                    json.append("\"fileType\":\"1\"");
                                    json.append("},");
                                    //文件处理完毕，删除临时文件
                                    if (FileHelper.deleteFileIfExists(receiptFile.getPath())) {
                                        WriteBankLogLn("已删除临时文件：" + receiptFile.getPath());
                                    }
                                    sb2.append(receiptFile.getName() + ",");
                                } else {
                                    WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                    continue;
                                }
                            }
                        }
                    } else {
                        WriteBankLogLn(fileName + "解压后文件为空");
                        //isZip = false;
                    }
                    /*if (isZip) {
                        String filePath = receiptSaveToMainDir + File.separator + actNum + File.separator + tranDate + File.separator;
                        if (isSaveOnlyFile) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(new Date());
                            calendar.add(Calendar.DAY_OF_MONTH, -2);
                            if (Format.Date8Format.parse(tranDate).before(calendar.getTime())) {
                                FileHelper.writeFile(filePath + actNum + "_" + tranDate + ".txt", "", getCharset());
                            }
                        }
                        if ("true".equals(bankFront.getStrValueByFor("isSaveReceiptFile", "")) && fileList.get(i).exists()) {
                            if (actNum != null) {
                                FileHelper.mkdir(filePath);
                                FileHelper.copyFile(fileList.get(i), new File(filePath + File.separator + fileName));
                            }
                        }
                    }*/
                    if (FileHelper.deleteFileIfExists(fileList.get(i).getPath())) {
                        WriteBankLogLn("已删除下载的压缩包文件：" + fileList.get(i).getPath());
                    }
                } else {
                    WriteBankLogLn("文件不存在：" + fileList.get(i).getPath());
                }
            }
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件,文件名为：" + sb2);
            if (tmpFileCount > 0) {
                json.deleteCharAt(json.length() - 1);
                json.append("]}");
//                WriteBankLogLn("推送数据到ATS的数据为：" + json.toString());
                String[] data;
                String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;

                if ("nbGateway".equals(receiptPushType)) {
                    WriteBankLogLn("3.推送给网关的数据" + json.toString());
                    data = FormSubmit.receiptInfoSend(json.toString(), this);
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到网关成功,请查看数据");
                    } else {
                        WriteBankLogLn("推送数据到网关失败");
                    }
                } else {
                    data = sendToATS(json.toString());
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到ATS成功,请查看数据");
                    } else {
                        WriteBankLogLn("推送数据到ATS失败");
                    }
                }

            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        }
    }


    public void deleteFile(String filePath) {
        //String filePath2 = "d://101_AWYiFq!v3TD_ea4ee_031090177520100171_20180928_2.zip";
        File fileGz = new File(filePath);
        //删除带.gz的压缩包 ?
        if (FileHelper.deleteFileIfExists(fileGz.getPath())) {
            System.out.println("success");
        } else {
            System.out.println("out");
        }
    }
}
